package com.sdp.irrigation.controller;


import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.irrigation.cache.EmpCache;
import com.sdp.irrigation.db.irrigation_emp.service.IIrrigationEmpService;
import com.sdp.irrigation.entity.IrrigationEmp;
import com.sdp.irrigation.utils.CommConstants;
import com.sdp.irrigation.utils.HttpClientUtil;
import com.sdp.irrigation.utils.IrrigationConstants;
import com.sdp.right.db.sys_emp.service.ISysEmpService;
import com.sdp.right.entity.SysEmp;
import com.sdp.right.service.RightExtService;

/**
 * <p>
 * 人员档案 前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-12-14
 */
@RestController
@RequestMapping("/IrrigationEmpController")
public class IrrigationEmpController {

	
	@Autowired
	private IIrrigationEmpService iIrrigationEmpService;

	@Autowired
	private Query query;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private RightExtService rightExtService;
	
	@Autowired
	private ISysEmpService iSysEmpService;
	
	@Autowired
	private HttpClientUtil httpClientUtil;
	
	@Autowired
	private EmpCache empCache;
	
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iIrrigationEmpService, IrrigationEmp.class, dataCenter));
	}
	
	@GetMapping(value = "/initIcNo")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> initIcNo() {
		QueryWrapper<IrrigationEmp> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().isNotNull(IrrigationEmp::getIdNo);
		List<IrrigationEmp> empList = iIrrigationEmpService.list(queryWrapper);
		List<IrrigationEmp> updateList = new ArrayList<>();
		for (IrrigationEmp irrigationEmp : empList) {
			if (!StringUtils.isEmpty(irrigationEmp.getIdNo())) {
				JSONObject result = httpClientUtil.getUserICInfo(null, irrigationEmp.getIdNo());
				if (result.containsKey("data") && result.getJSONObject("data").containsKey("initCode")) {
					irrigationEmp.setEmpIc(result.getJSONObject("data").getString("initCode"));
					updateList.add(irrigationEmp);
				}
			}
		}
		if (updateList.size() > 0) {
			iIrrigationEmpService.updateBatchById(updateList);
			//删除缓存
			for (IrrigationEmp irrigationEmp : updateList) {
				empCache.deleteCache(irrigationEmp.getEmpIc());
			}
		}
		return Result.ok();
	} 
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody IrrigationEmp emp) throws NoSuchAlgorithmException {
		if(emp==null) {
			return Result.error("人员信息为空");
		}
		
		SysEmp sysEmp = new SysEmp();
		sysEmp.setOrgNo(IrrigationConstants.默认公司编码.getCode());
		BeanUtils.copyProperties(emp, sysEmp);
		
		
		if(StringUtils.isEmpty(emp.getKeyId())) {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iIrrigationEmpService, IrrigationEmp.class, new String[] {"empNo","accountNo"}, "keyId", emp, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("人员工号和账号不能重复");
			}
			emp.setCreateTime(LocalDateTime.now());
			emp.setUpdateTime(LocalDateTime.now());
			iIrrigationEmpService.save(emp);
			
			//向账号表中添加人员
			
			rightExtService.addSysEmp(sysEmp);
			
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iIrrigationEmpService, IrrigationEmp.class, new String[] {"empNo","accountNo"}, "keyId", null, emp, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("人员工号和账号不能重复");
			}
			emp.setUpdateTime(LocalDateTime.now());
			//更新的时候如果卡号修改，余额设置为0
			if (!StringUtils.isEmpty(emp.getEmpIc())) {
				if (!CommConstants.isProvinceIcNo(emp.getEmpIc())) {
					QueryWrapper<IrrigationEmp> queryWrapper = new QueryWrapper<>();
					queryWrapper.lambda().eq(IrrigationEmp::getEmpNo, emp.getEmpNo());
					IrrigationEmp empOld = iIrrigationEmpService.getOne(queryWrapper, false);
					if (empOld != null && !emp.getEmpIc().equals(empOld.getEmpIc())) {
						emp.setIcMoney(BigDecimal.ZERO);
					}
				}
			} else {
				emp.setIcMoney(BigDecimal.ZERO);
			}
			
			
			iIrrigationEmpService.updateById(emp);
			
			//更新账号表中人员信息
			sysEmp.setKeyId(null);
			rightExtService.updateSysEmpByAccountNo(emp.getAccountNo(), sysEmp);
		}
		
		//删除缓存
		if (!StringUtils.isEmpty(emp.getEmpIc())) {
			empCache.deleteCache(emp.getEmpIc());
		}

		return Result.ok();
	}
	
	@PostMapping(value = "/changeProfilePicture")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> changeProfilePicture(@RequestBody SysEmp sysEmp){
		if(StringUtils.isEmpty(sysEmp)) {
			return Result.error("人员信息不存在");
		}
		
		LambdaUpdateWrapper<SysEmp> sysEmpUpdateWrapper = new LambdaUpdateWrapper<>();
		sysEmpUpdateWrapper.eq(SysEmp::getAccountNo, sysEmp.getAccountNo());
		sysEmpUpdateWrapper.set(SysEmp::getProfilePicture, sysEmp.getProfilePicture());
		iSysEmpService.update(sysEmpUpdateWrapper);
		
		LambdaUpdateWrapper<IrrigationEmp> empUpdateWrapper = new LambdaUpdateWrapper<>();
		empUpdateWrapper.eq(IrrigationEmp::getAccountNo, sysEmp.getAccountNo());
		empUpdateWrapper.set(IrrigationEmp::getProfilePicture, sysEmp.getProfilePicture());
		iIrrigationEmpService.update(empUpdateWrapper);
		
		
		return Result.ok();
		
	}
}

